package pannel.book;

import pannel.user.User;
import system.BasePage;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.io.File;

public class BookManagementPage extends BasePage {
    private static final Map<String, Set<String>> BUTTON_ROLE_MAPPING = new HashMap<>();
    private DefaultTableModel model;
    private List<Book> bookList = new ArrayList<>();
    private JTable table;
    private JTextField searchField;
    private int currentPage = 1;
    private int pageSize = 10;
    private JLabel pageInfoLabel;
    private BookDao bookDao;
    private int totalRecords = 0;
    private JPanel previewPanel;
    private JLabel imageLabel;

    static {
        // 只允许管理员使用的按钮
        BUTTON_ROLE_MAPPING.put("addButton", new HashSet<>(Collections.singletonList(User.ROLE_ADMIN)));
        BUTTON_ROLE_MAPPING.put("deleteButton", new HashSet<>(Collections.singletonList(User.ROLE_ADMIN)));
        BUTTON_ROLE_MAPPING.put("editButton", new HashSet<>(Collections.singletonList(User.ROLE_ADMIN)));
    }

    private static class NonEditableTableModel extends DefaultTableModel {
        public NonEditableTableModel(Object[][] data, Object[] columnNames) {
            super(data, columnNames);
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    }

    public BookManagementPage(User user) {
        super(user);
        bookDao = new BookDao();
        initPageContent();
    }

    @Override
    protected void initPageContent() {
        setPageTitle("图书管理");
        setupContent();
        setupPreviewPanel();
        refreshTable();
    }

    private void setupPreviewPanel() {
        previewPanel = new JPanel();
        previewPanel.setPreferredSize(new Dimension(200, 0));
        previewPanel.setBorder(BorderFactory.createTitledBorder("图书封面预览"));
        previewPanel.setLayout(new BorderLayout());

        imageLabel = new JLabel();
        imageLabel.setHorizontalAlignment(JLabel.CENTER);
        imageLabel.setText("暂无图片");
        previewPanel.add(imageLabel, BorderLayout.CENTER);

        contentArea.add(previewPanel, BorderLayout.EAST);
    }

    private void updatePreviewImage(String imagePath) {
        if (imagePath != null && !imagePath.isEmpty()) {
            ImageIcon imageIcon = new ImageIcon(imagePath);
            Image image = imageIcon.getImage().getScaledInstance(180, 240, Image.SCALE_SMOOTH);
            imageLabel.setIcon(new ImageIcon(image));
            imageLabel.setText("");
        } else {
            imageLabel.setIcon(null);
            imageLabel.setText("暂无图片");
        }
    }

    private void refreshTable() {
        SwingUtilities.invokeLater(() -> {
            try {
                String searchText = searchField.getText().trim();
                bookList = bookDao.pageQuery(searchText, currentPage, pageSize);
                totalRecords = bookDao.getTotalCount(searchText);

                model.setRowCount(0);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                for (Book book : bookList) {
                    Object[] rowData;
                    // 根据用户角色决定是否显示借阅人ID
                    if (User.ROLE_ADMIN.equals(getCurrentUser().getRole())) {
                        rowData = new Object[]{
                                book.getId(),
                                book.getName(),
                                book.getAuthor(),
                                book.getPublisher(),
                                book.getStatus() == Book.STATUS_AVAILABLE ? "可借" : "已借出",
                                book.getBorrowerId() == null ? "" : book.getBorrowerId(),
                                book.getBorrowTime() == null ? "" : sdf.format(book.getBorrowTime())
                        };
                    } else {
                        rowData = new Object[]{
                                book.getId(),
                                book.getName(),
                                book.getAuthor(),
                                book.getPublisher(),
                                book.getStatus() == Book.STATUS_AVAILABLE ? "可借" : "已借出",
                                book.getBorrowTime() == null ? "" : sdf.format(book.getBorrowTime())
                        };
                    }
                    model.addRow(rowData);
                }
                updatePageInfo();
                table.repaint();
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(this, "获取图书数据失败：" + e.getMessage());
            }
        });
    }

    private void updatePageInfo() {
        int totalPages = (int) Math.ceil((double) totalRecords / pageSize);
        pageInfoLabel.setText(String.format("第 %d/%d 页  共%d条记录", currentPage, totalPages, totalRecords));
    }

    private JButton createRoleButton(String buttonText, String buttonId) {
        JButton button = new JButton(buttonText);
        Set<String> allowedRoles = BUTTON_ROLE_MAPPING.getOrDefault(buttonId, Collections.emptySet());
        button.setVisible(allowedRoles.contains(getCurrentUser().getRole()));
        return button;
    }private void setupContent() {
        contentArea.setLayout(new BorderLayout());
        JPanel topPanel = new JPanel(new BorderLayout());

        // 搜索面板
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        searchField = new JTextField(20);
        JButton searchButton = new JButton("搜索");
        searchPanel.add(new JLabel("书名："));
        searchPanel.add(searchField);
        searchPanel.add(searchButton);

        // 工具栏
        JPanel toolBar = new JPanel(new FlowLayout(FlowLayout.LEFT));
        toolBar.setBackground(Color.WHITE);

        // 创建按钮并根据角色控制显示
        JButton addButton = createRoleButton("新增图书", "addButton");
        JButton deleteButton = createRoleButton("删除图书", "deleteButton");
        JButton editButton = createRoleButton("编辑图书", "editButton");
        JButton borrowButton = new JButton("借阅");

        toolBar.add(addButton);
        toolBar.add(deleteButton);
        toolBar.add(editButton);
        toolBar.add(borrowButton);

        topPanel.add(searchPanel, BorderLayout.NORTH);
        topPanel.add(toolBar, BorderLayout.CENTER);

        // 表格设置 - 根据用户角色决定显示的列
        String[] columnNames;
        if (User.ROLE_ADMIN.equals(getCurrentUser().getRole())) {
            columnNames = new String[]{"ID", "书名", "作者", "出版社", "状态", "借阅人ID", "借阅时间"};
        } else {
            columnNames = new String[]{"ID", "书名", "作者", "出版社", "状态", "借阅时间"};
        }
        model = new NonEditableTableModel(new Object[0][], columnNames);
        table = new JTable(model);

        // 表格渲染
        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment(JLabel.CENTER);
        for (int i = 0; i < table.getColumnCount(); i++) {
            table.getColumnModel().getColumn(i).setCellRenderer(centerRenderer);
        }

        // 添加表格选择监听器
        table.getSelectionModel().addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                int selectedRow = table.getSelectedRow();
                if (selectedRow != -1) {
                    Book selectedBook = bookList.get(selectedRow);
                    updatePreviewImage(selectedBook.getImagePath());
                }
            }
        });

        table.getTableHeader().setReorderingAllowed(false);
        table.setRowHeight(30);

        // 设置列宽
        table.getColumnModel().getColumn(0).setPreferredWidth(50);   // ID
        table.getColumnModel().getColumn(1).setPreferredWidth(150);  // 书名
        table.getColumnModel().getColumn(2).setPreferredWidth(100);  // 作者
        table.getColumnModel().getColumn(3).setPreferredWidth(150);  // 出版社
        table.getColumnModel().getColumn(4).setPreferredWidth(80);   // 状态
        if (User.ROLE_ADMIN.equals(getCurrentUser().getRole())) {
            table.getColumnModel().getColumn(5).setPreferredWidth(80);   // 借阅人ID
            table.getColumnModel().getColumn(6).setPreferredWidth(150);  // 借阅时间
        } else {
            table.getColumnModel().getColumn(5).setPreferredWidth(150);  // 借阅时间
        }

        // 分页面板
        JPanel paginationPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JButton prevButton = new JButton("上一页");
        JButton nextButton = new JButton("下一页");
        pageInfoLabel = new JLabel();

        paginationPanel.add(prevButton);
        paginationPanel.add(pageInfoLabel);
        paginationPanel.add(nextButton);

        // 分页按钮事件
        prevButton.addActionListener(e -> {
            if (currentPage > 1) {
                currentPage--;
                refreshTable();
            }
        });

        nextButton.addActionListener(e -> {
            int totalPages = (int) Math.ceil((double) totalRecords / pageSize);
            if (currentPage < totalPages) {
                currentPage++;
                refreshTable();
            }
        });

        searchButton.addActionListener(e -> {
            currentPage = 1;
            refreshTable();
        });

        // 新增图书按钮事件
        addButton.addActionListener(e -> {
            BookDialog dialog = new BookDialog(SwingUtilities.getWindowAncestor(this), null);
            if (dialog.showDialog()) {
                try {
                    Book newBook = Book.builder()
                            .name(dialog.getBookName())
                            .author(dialog.getAuthor())
                            .publisher(dialog.getPublisher())
                            .status(Book.STATUS_AVAILABLE)
                            .imagePath(dialog.getImagePath())
                            .build();

                    if (bookDao.insert(newBook)) {
                        JOptionPane.showMessageDialog(this, "添加图书成功！");
                        refreshTable();
                    } else {
                        JOptionPane.showMessageDialog(this, "添加图书失败！");
                    }
                } catch (SQLException ex) {
                    JOptionPane.showMessageDialog(this, "添加图书失败：" + ex.getMessage());
                }
            }
        });

        // 删除图书按钮事件
        deleteButton.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow != -1) {
                int id = (Integer) table.getValueAt(selectedRow, 0);
                int confirm = JOptionPane.showConfirmDialog(this,
                        "确定要删除该图书吗？", "确认删除",
                        JOptionPane.YES_NO_OPTION);

                if (confirm == JOptionPane.YES_OPTION) {
                    try {
                        if (bookDao.deleteById(id)) {
                            JOptionPane.showMessageDialog(this, "删除成功！");
                            refreshTable();
                        } else {
                            JOptionPane.showMessageDialog(this, "删除失败！");
                        }
                    } catch (SQLException ex) {
                        JOptionPane.showMessageDialog(this, "删除失败：" + ex.getMessage());
                    }
                }
            } else {
                JOptionPane.showMessageDialog(this, "请选择要删除的图书");
            }
        });

        // 编辑图书按钮事件
        editButton.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow != -1) {
                Book selectedBook = bookList.get(selectedRow);
                BookDialog dialog = new BookDialog(SwingUtilities.getWindowAncestor(this), selectedBook);
                if (dialog.showDialog()) {
                    try {
                        selectedBook.setName(dialog.getBookName());
                        selectedBook.setAuthor(dialog.getAuthor());
                        selectedBook.setPublisher(dialog.getPublisher());
                        selectedBook.setImagePath(dialog.getImagePath());

                        if (bookDao.updateById(selectedBook)) {
                            JOptionPane.showMessageDialog(this, "更新成功！");
                            refreshTable();
                        } else {
                            JOptionPane.showMessageDialog(this, "更新失败！");
                        }
                    } catch (SQLException ex) {
                        JOptionPane.showMessageDialog(this, "更新失败：" + ex.getMessage());
                    }
                }
            } else {
                JOptionPane.showMessageDialog(this, "请选择要编辑的图书");
            }
        });

        // 借书按钮事件
        borrowButton.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow != -1) {
                Book book = bookList.get(selectedRow);
                if (book.getStatus() == Book.STATUS_AVAILABLE) {
                    try {
                        if (bookDao.borrowBook(book.getId(), getCurrentUser().getId())) {
                            JOptionPane.showMessageDialog(this, "借阅成功！");
                            refreshTable();
                        } else {
                            JOptionPane.showMessageDialog(this, "借阅失败！");
                        }
                    } catch (SQLException ex) {
                        JOptionPane.showMessageDialog(this, "借阅失败：" + ex.getMessage());
                    }
                } else {
                    JOptionPane.showMessageDialog(this, "该图书已被借出");
                }
            } else {
                JOptionPane.showMessageDialog(this, "请选择要借阅的图书");
            }
        });


        JScrollPane scrollPane = new JScrollPane(table);
        contentArea.add(topPanel, BorderLayout.NORTH);
        contentArea.add(scrollPane, BorderLayout.CENTER);
        contentArea.add(paginationPanel, BorderLayout.SOUTH);
    }
}class BookDialog extends JDialog {
    private JTextField nameField;
    private JTextField authorField;
    private JTextField publisherField;
    private JLabel imagePreviewLabel;
    private JTextField imagePathField;
    private String selectedImagePath;
    private boolean confirmed = false;
    private Book book;
    private static final int PREVIEW_WIDTH = 160;
    private static final int PREVIEW_HEIGHT = 200;

    public BookDialog(Window owner, Book book) {
        super(owner, book == null ? "新增图书" : "编辑图书", ModalityType.APPLICATION_MODAL);
        this.book = book;
        if (book != null) {
            this.selectedImagePath = book.getImagePath();
        }
        setupDialog();
    }

    private void setupDialog() {
        JPanel mainPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.anchor = GridBagConstraints.WEST;

        // 书名
        addField(mainPanel, gbc, "书名:", nameField = new JTextField(20), 0);

        // 作者
        addField(mainPanel, gbc, "作者:", authorField = new JTextField(20), 1);

        // 出版社
        addField(mainPanel, gbc, "出版社:", publisherField = new JTextField(20), 2);

        // 图片路径
        JPanel imagePanel = new JPanel(new BorderLayout(5, 0));
        imagePathField = new JTextField(15);
        imagePathField.setEditable(false);
        JButton browseButton = new JButton("浏览...");
        imagePanel.add(imagePathField, BorderLayout.CENTER);
        imagePanel.add(browseButton, BorderLayout.EAST);

        addField(mainPanel, gbc, "封面图片:", imagePanel, 3);

        // 图片预览区域
        gbc.gridy = 4;
        gbc.gridx = 0;
        gbc.gridwidth = 3;
        gbc.fill = GridBagConstraints.BOTH;
        imagePreviewLabel = new JLabel();
        imagePreviewLabel.setPreferredSize(new Dimension(PREVIEW_WIDTH, PREVIEW_HEIGHT));
        imagePreviewLabel.setBorder(BorderFactory.createEtchedBorder());
        imagePreviewLabel.setHorizontalAlignment(JLabel.CENTER);
        mainPanel.add(imagePreviewLabel, gbc);

        // 浏览按钮事件
        browseButton.addActionListener(e -> {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileFilter(new FileNameExtensionFilter(
                    "图片文件 (*.jpg, *.png, *.gif)", "jpg", "jpeg", "png", "gif"));

            if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                File selectedFile = fileChooser.getSelectedFile();
                selectedImagePath = selectedFile.getAbsolutePath();
                imagePathField.setText(selectedFile.getName());
                updateImagePreview(selectedImagePath);
            }
        });

        // 填充现有数据
        if (book != null) {
            nameField.setText(book.getName());
            authorField.setText(book.getAuthor());
            publisherField.setText(book.getPublisher());
            if (book.getImagePath() != null) {
                imagePathField.setText(new File(book.getImagePath()).getName());
                updateImagePreview(book.getImagePath());
            }
        }

        // 按钮面板
        JPanel buttonPanel = new JPanel();
        JButton okButton = new JButton("确定");
        JButton cancelButton = new JButton("取消");

        okButton.addActionListener(e -> {
            if (validateInput()) {
                confirmed = true;
                dispose();
            }
        });

        cancelButton.addActionListener(e -> dispose());

        buttonPanel.add(okButton);
        buttonPanel.add(cancelButton);

        // 设置对话框属性
        setLayout(new BorderLayout());
        add(mainPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        pack();
        setLocationRelativeTo(getOwner());
        setResizable(false);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    private void updateImagePreview(String imagePath) {
        if (imagePath != null && !imagePath.isEmpty()) {
            ImageIcon imageIcon = new ImageIcon(imagePath);
            Image image = imageIcon.getImage().getScaledInstance(
                    PREVIEW_WIDTH, PREVIEW_HEIGHT, Image.SCALE_SMOOTH);
            imagePreviewLabel.setIcon(new ImageIcon(image));
            imagePreviewLabel.setText("");
        } else {
            imagePreviewLabel.setIcon(null);
            imagePreviewLabel.setText("无预览图片");
        }
    }

    private void addField(JPanel panel, GridBagConstraints gbc, String label, JComponent component, int y) {
        gbc.gridx = 0;
        gbc.gridy = y;
        gbc.gridwidth = 1;
        panel.add(new JLabel(label), gbc);

        gbc.gridx = 1;
        gbc.gridwidth = 2;
        panel.add(component, gbc);
    }

    private boolean validateInput() {
        String name = getBookName();
        String author = getAuthor();
        String publisher = getPublisher();

        if (name.isEmpty()) {
            JOptionPane.showMessageDialog(this, "书名不能为空");
            nameField.requestFocus();
            return false;
        }

        if (author.isEmpty()) {
            JOptionPane.showMessageDialog(this, "作者不能为空");
            authorField.requestFocus();
            return false;
        }

        if (publisher.isEmpty()) {
            JOptionPane.showMessageDialog(this, "出版社不能为空");
            publisherField.requestFocus();
            return false;
        }

        return true;
    }

    public boolean showDialog() {
        setVisible(true);
        return confirmed;
    }

    public String getBookName() {
        return nameField.getText().trim();
    }

    public String getAuthor() {
        return authorField.getText().trim();
    }

    public String getPublisher() {
        return publisherField.getText().trim();
    }

    public String getImagePath() {
        return selectedImagePath;
    }
}